import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Avatar, Tag, Modal, Form, Input, Select, message, Row, Col, Statistic, Typography, Tooltip, Badge, Dropdown, Menu } from 'antd';
import { UserOutlined, EditOutlined, DeleteOutlined, PlusOutlined, SearchOutlined, MoreOutlined, PhoneOutlined, MailOutlined, CalendarOutlined, ShoppingCartOutlined, DollarOutlined, CrownOutlined, ExportOutlined, ReloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import BaseTable from '../shared/table/BaseTable';
import api from '../utils/api';
import { getErrorMessage, getSuccessMessage, getHttpErrorMessage, PAGES, ERROR_TYPES, SUCCESS_TYPES } from '../utils/i18n';
import '../styles/Users.css';

const { Title, Text } = Typography;
const { Option } = Select;

const Users = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [exportLoading, setExportLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [levelFilter, setLevelFilter] = useState('all');

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        setLoading(true);
        const response = await api.get('/admin/users');
        if (response.data.success) {
          setUsers(response.data.data.users);
        } else {
          message.error(response.data.message || '获取用户列表失败');
        }
      } catch (error) {
        message.error('获取用户列表失败');
      } finally {
        setLoading(false);
      }
    };

    fetchUsers();
  }, []);

  const [stats, setStats] = useState({
    totalUsers: 0,
    activeUsers: 0,
    vipUsers: 0,
    totalRevenue: 0
  });

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const response = await api.get('/admin/users/statistics');
        if (response.data.success) {
          setStats(response.data.data);
        } else {
          message.error(response.data.message || '获取统计数据失败');
        }
      } catch (error) {
        message.error('获取统计数据失败');
      }
    };

    fetchStats();
  }, []);

  const getStatusColor = (status) => {
    const colors = {
      active: 'success',
      inactive: 'warning',
      banned: 'error'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status) => {
    const texts = {
      active: '活跃',
      banned: '已封禁'
    };
    return texts[status] || status;
  };

  const getLevelColor = (level) => {
    const colors = {
      regular: 'default',
      vip: 'gold',
      premium: 'purple'
    };
    return colors[level] || 'default';
  };

  const getLevelText = (level) => {
    const texts = {
      regular: '普通用户',
      vip: 'VIP用户',
      premium: '高级用户'
    };
    return texts[level] || level;
  };

  const getLevelIcon = (level) => {
    if (level === 'vip' || level === 'premium') {
      return <CrownOutlined style={{ color: level === 'premium' ? '#722ed1' : '#faad14' }} />;
    }
    return null;
  };

  const handleEdit = (user) => {
    setEditingUser(user);
    form.setFieldsValue({
      name: user.username,
      email: user.email,
      phone: user.phone,
      status: user.is_active ? 'active' : 'banned',
      level: user.membership_level,
      address: user.address,
    });
    setModalVisible(true);
  };

  const handleDelete = (userId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个用户吗？此操作不可恢复。',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await api.delete(`/admin/users/${userId}`);
          if (response.data.success) {
            setUsers(users.filter(user => user.user_id !== userId));
            message.success(getSuccessMessage(PAGES.USERS, SUCCESS_TYPES.DELETE_SUCCESS));
          } else {
            message.error(response.data.message || getErrorMessage(PAGES.USERS, ERROR_TYPES.DELETE_FAILED));
          }
        } catch (error) {
          message.error(getErrorMessage(PAGES.USERS, ERROR_TYPES.DELETE_FAILED));
        }
      }
    });
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      const userData = {
        username: values.name,
        email: values.email,
        phone: values.phone,
        is_active: values.status === 'active',
        membership_level: values.level,
        address: values.address,
      };

      if (editingUser) {
        // Edit user
        const response = await api.put(`/admin/users/${editingUser.user_id}`, userData);
        if (response.data.success) {
          const fetchResponse = await api.get('/admin/users');
          if (fetchResponse.data.success) {
            setUsers(fetchResponse.data.data.users);
          }
          message.success(getSuccessMessage(PAGES.USERS, SUCCESS_TYPES.UPDATE_SUCCESS));
        } else {
          message.error(response.data.message || getErrorMessage(PAGES.USERS, ERROR_TYPES.UPDATE_FAILED));
        }
      } else {
        // Add user
        const response = await api.post('/admin/users', { ...userData, password: values.password });
        if (response.data.success) {
          const fetchResponse = await api.get('/admin/users');
          if (fetchResponse.data.success) {
            setUsers(fetchResponse.data.data.users);
          }
          message.success(getSuccessMessage(PAGES.USERS, SUCCESS_TYPES.SAVE_SUCCESS));
        } else {
          message.error(response.data.message || getErrorMessage(PAGES.USERS, ERROR_TYPES.SAVE_FAILED));
        }
      }
      
      setModalVisible(false);
      setEditingUser(null);
      form.resetFields();
    } catch (error) {
      message.error(getErrorMessage(PAGES.USERS, ERROR_TYPES.SAVE_FAILED));
    } finally {
      setLoading(false);
    }
  };

  const handleStatusChange = async (userId, newStatus) => {
    try {
      const response = await api.put(`/admin/users/${userId}/status`, { is_active: newStatus });
      if (response.data.success) {
        const fetchResponse = await api.get('/admin/users');
        if (fetchResponse.data.success) {
          setUsers(fetchResponse.data.data.users);
        }
        message.success(getSuccessMessage(PAGES.USERS, SUCCESS_TYPES.STATUS_UPDATE_SUCCESS));
      } else {
        message.error(response.data.message || getErrorMessage(PAGES.USERS, ERROR_TYPES.STATUS_UPDATE_FAILED));
      }
    } catch (error) {
      message.error(getErrorMessage(PAGES.USERS, ERROR_TYPES.STATUS_UPDATE_FAILED));
    }
  };

  const handleExport = async () => {
    try {
      setExportLoading(true);
      const response = await api.get('/admin/users/export', {
        responseType: 'blob'
      });
      
      const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `用户列表_${dayjs().format('YYYY-MM-DD')}.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    } finally {
      setExportLoading(false);
    }
  };

  const filteredUsers = users.filter(user => {
    const lowerSearchText = searchText.toLowerCase();
    const matchesSearch = (user.username && user.username.toLowerCase().includes(lowerSearchText)) ||
                         (user.email && user.email.toLowerCase().includes(lowerSearchText)) ||
                         (user.phone && user.phone.includes(searchText));
    
    let matchesStatus = true;
    if (statusFilter !== 'all') {
      if (statusFilter === 'active') {
        matchesStatus = user.is_active;
      } else if (statusFilter === 'banned') {
        matchesStatus = !user.is_active;
      }
    }

    const matchesLevel = levelFilter === 'all' || user.membership_level === levelFilter;
    
    return matchesSearch && matchesStatus && matchesLevel;
  });



  const getActionMenu = (user) => (
    <Menu>
      <Menu.Item key="edit" icon={<EditOutlined />} onClick={() => handleEdit(user)}>
        编辑信息
      </Menu.Item>
      {user.is_active ? (
        <Menu.Item key="ban" onClick={() => handleStatusChange(user.user_id, false)}>
          封禁用户
        </Menu.Item>
      ) : (
        <Menu.Item key="active" onClick={() => handleStatusChange(user.user_id, true)}>
          设为活跃
        </Menu.Item>
      )}
      <Menu.Divider />
      <Menu.Item key="delete" icon={<DeleteOutlined />} danger onClick={() => handleDelete(user.user_id)}>
        删除用户
      </Menu.Item>
    </Menu>
  );

  const columns = [
    {
      title: '用户',
      dataIndex: 'username',
      key: 'user',
      width: 200,
      render: (text, record) => (
        <Space>
          <Avatar src={record.avatar} icon={<UserOutlined />} />
          <span>{record.username}</span>
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'status',
      width: 100,
      render: status => (
        <Tag color={status ? 'success' : 'error'}>
          {status ? '活跃' : '封禁'}
        </Tag>
      ),
    },
    {
      title: '会员等级',
      dataIndex: 'membership_level',
      key: 'level',
      width: 120,
      render: level => <Tag color={getLevelColor(level)}>{getLevelText(level)}</Tag>,
    },
    {
      title: '最后登录',
      dataIndex: 'last_login_at',
      key: 'lastLogin',
      width: 180,
      render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '-',
    },
    {
      title: '注册时间',
      dataIndex: 'created_at',
      key: 'registrationDate',
      width: 180,
      render: (text) => dayjs(text).format('YYYY-MM-DD'),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 150,
      render: (text, record) => (
        <Dropdown overlay={getActionMenu(record)} trigger={['click']}>
          <Button icon={<MoreOutlined />} />
        </Dropdown>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px', backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
      <div style={{ 
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        borderRadius: '16px',
        padding: '24px',
        marginBottom: '24px',
        boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <div style={{
            width: '64px',
            height: '64px',
            borderRadius: '16px',
            background: 'rgba(255, 255, 255, 0.2)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '28px',
            color: 'white'
          }}>
            <UserOutlined />
          </div>
          <div>
            <Title level={2} style={{ margin: 0, color: 'white', fontSize: '28px' }}>
              用户管理
            </Title>
            <p style={{ margin: '8px 0 0 0', color: 'rgba(255, 255, 255, 0.8)', fontSize: '16px' }}>管理用户信息、等级权限和消费记录</p>
          </div>
        </div>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} lg={6}>
          <Card style={{
            borderRadius: '12px',
            border: 'none',
            boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)',
            background: 'white',
            position: 'relative',
            overflow: 'hidden'
          }}>
            <div style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              height: '4px',
              background: 'linear-gradient(90deg, #667eea 0%, #764ba2 100%)'
            }} />
            <Statistic
              title="总用户数"
              value={stats.total || 0}
              prefix={
                <div style={{
                  width: '40px',
                  height: '40px',
                  borderRadius: '8px',
                  background: 'rgba(102, 126, 234, 0.1)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#667eea',
                  fontSize: '20px',
                  marginRight: '12px'
                }}>
                  <UserOutlined />
                </div>
              }
              valueStyle={{ color: '#667eea', fontSize: '24px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card style={{
            borderRadius: '12px',
            border: 'none',
            boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)',
            background: 'white',
            position: 'relative',
            overflow: 'hidden'
          }}>
            <div style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              height: '4px',
              background: 'linear-gradient(90deg, #11998e 0%, #38ef7d 100%)'
            }} />
            <Statistic
              title="活跃用户"
              value={stats.active || 0}
              prefix={
                <div style={{
                  width: '40px',
                  height: '40px',
                  borderRadius: '8px',
                  background: 'rgba(17, 153, 142, 0.1)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#11998e',
                  fontSize: '20px',
                  marginRight: '12px'
                }}>
                  <UserOutlined />
                </div>
              }
              valueStyle={{ color: '#11998e', fontSize: '24px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card style={{
            borderRadius: '12px',
            border: 'none',
            boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)',
            background: 'white',
            position: 'relative',
            overflow: 'hidden'
          }}>
            <div style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              height: '4px',
              background: 'linear-gradient(90deg, #4facfe 0%, #00f2fe 100%)'
            }} />
            <Statistic
              title="本月新增"
              value={stats.newThisMonth || 0}
              prefix={
                <div style={{
                  width: '40px',
                  height: '40px',
                  borderRadius: '8px',
                  background: 'rgba(79, 172, 254, 0.1)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#4facfe',
                  fontSize: '20px',
                  marginRight: '12px'
                }}>
                  <CalendarOutlined />
                </div>
              }
              valueStyle={{ color: '#4facfe', fontSize: '24px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card style={{
            borderRadius: '12px',
            border: 'none',
            boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)',
            background: 'white',
            position: 'relative',
            overflow: 'hidden'
          }}>
            <div style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              height: '4px',
              background: 'linear-gradient(90deg, #f6d365 0%, #fda085 100%)'
            }} />
            <Statistic
              title="今日新增"
              value={stats.newToday || 0}
              prefix={
                <div style={{
                   width: '40px',
                   height: '40px',
                   borderRadius: '8px',
                   background: 'rgba(246, 211, 101, 0.2)',
                   display: 'flex',
                   alignItems: 'center',
                   justifyContent: 'center',
                   color: '#f6b965',
                   fontSize: '20px',
                   marginRight: '12px'
                 }}>
                   <PlusOutlined />
                 </div>
               }
               valueStyle={{ color: '#f6b965', fontSize: '24px', fontWeight: 'bold' }}
             />
           </Card>
         </Col>
       </Row>

      {/* 用户列表 */}
      <Card 
        bodyStyle={{ padding: 0 }}
        style={{ 
          borderRadius: '16px', 
          boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
          overflow: 'hidden'
        }}
      >
        <BaseTable
          dataSource={filteredUsers}
          columns={columns}
          loading={loading}
          rowKey="id"
          className="user-management-table"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
          }}
        />
      </Card>

      {/* 编辑/添加用户模态框 */}
      <Modal
        title={editingUser ? '编辑用户' : '添加用户'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => {
          setModalVisible(false);
          setEditingUser(null);
          form.resetFields();
        }}
        confirmLoading={loading}
        width={600}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          style={{ marginTop: '20px' }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  <Option value="active">活跃</Option>
                  <Option value="inactive">不活跃</Option>
                  <Option value="banned">已封禁</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="level"
                label="用户等级"
                rules={[{ required: true, message: '请选择用户等级' }]}
              >
                <Select placeholder="请选择用户等级">
                  <Option value="regular">普通用户</Option>
                  <Option value="vip">VIP用户</Option>
                  <Option value="premium">高级用户</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="address"
            label="地址"
          >
            <Input.TextArea rows={3} placeholder="请输入地址" />
          </Form.Item>
          {!editingUser && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default Users;